package com.gdcp.controller.backend;

import com.gdcp.beans.*;
import com.gdcp.common.ResponseModel;
import com.gdcp.config.RequestHolder;
import com.gdcp.service.CategoryService;
import com.gdcp.service.ProductService;
import com.gdcp.service.ShopService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.catalina.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/render/shopManager")
public class ShopController_backend {

    @Autowired
    ResponseModel responseModel;
    @Autowired
    ShopService shopService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    ProductService productService;
    @Autowired
    CommonCode commonCode;

    @RequestMapping(value = "/insert",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> insert(HttpServletRequest request){
        HttpSession session= RequestHolder.getSession();
        Shop shop=getShop(request, session);
        return shopService.insert(shop);
    }

    @RequestMapping(value = "updateByShopId",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> updateByShopId(){
        HttpSession session= RequestHolder.getSession();
        HttpServletRequest request=RequestHolder.getRequest();
        Shop shop=getShop(request, session);

        return shopService.updateByShopId(shop);
    }

    @PreAuthorize("hasAuthority('ROLE_SHOP_ADMIN')")
    @RequestMapping(value = "queryByShopId",method = RequestMethod.GET)
    public String queryByShopId(){
        //获取该店铺所有分类信息
        //List<Category> categories= categoryService.queryAllByShopId(2);
        HttpServletRequest request=RequestHolder.getRequest();
        User user= (User) RequestHolder.getSession("user");
        List<Category> categories= categoryService.queryAllByShopId(user.getShop_id());
        request.setAttribute("categories",categories);

        //获取该店铺所有商品-----限制商品数量
        //List<Product> products= productService.queryAllByShopId(2);

        //for (Category category:categories){
        //    List<Product> product=productService.queryProductsByCid(category.getId());
        //}
        List<Product> products= productService.queryAllByShopId(user.getShop_id());
        request.setAttribute("products",products);

        Shop shop=shopService.queryShopInfoByShopId(user.getShop_id());
        //System.out.println("shop="+shop);

        request.setAttribute("shop",shop);
        return "admin/shopManager";
    }

    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> list(int pageSize, int pageNumber, String sortName, String sortOrder){
        Map<String,Object> model=commonCode.getList(pageSize,pageNumber,sortName,sortOrder);
        return shopService.findPageBreakByCondition(model);
    }

    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @RequestMapping(value = "/remove",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> remove(Integer[] ids){
        if (ids==null){
            return responseModel.setModel(false,"请至少选择一条记录");
        }
        return shopService.removeByPrimaryKey(ids);
    }

    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> add(Shop shop){
        shopService.register(shop);
        return responseModel.setModel(true, "添加成功，新店铺---"+ shop.getShop_name());
    }

    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> edit(Shop shop){
        return shopService.updateInformation(shop);
    }

    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @RequestMapping(value = "/get/{id}",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> get(@PathVariable Integer id){
        Shop shop=shopService.getInformation(id);
        if (shop==null){
            return responseModel.setModel(false,"获取失败");
        }

        return responseModel.setModel(true,shop);
    }

    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @RequestMapping(value = "/search",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> search(String searchText){
        String str = "["+searchText+"]";
        JSONArray json= JSONArray.fromObject(str);
        Map<String, Object> param=new HashMap<>();

        for(int i=0;i<json.size();i++){
            JSONObject jsonOne = json.getJSONObject(i);
            param.put("id", jsonOne.getString("id"));
            System.out.println("jsonOne.getString(\"id\")"+jsonOne.getString("id"));
            param.put("shop_name", jsonOne.getString("shop_name"));
            param.put("user_id", jsonOne.getString("user_id"));
        }
        return shopService.searchInformation(param);
    }

    private Shop getShop(HttpServletRequest request,HttpSession session) {
        String shop_name= request.getParameter("shop_name");
        String shop_open_time= request.getParameter("shop_open_time");
        String shop_introduce= request.getParameter("shop_introduce");
        String shop_main_recommend= request.getParameter("shop_main_recommend");
        String shop_special_recommend_one= request.getParameter("shop_special_recommend_one");
        String shop_special_recommend_two= request.getParameter("shop_special_recommend_two");
        String shop_notice= request.getParameter("shop_notice");

        Shop shop=new Shop();
        User user= (User) session.getAttribute("user");
        //System.out.println(user);
        if (user.getId()!=null){
            shop.setId(user.getShop_id());
        }

        if (shop_name!=null){
            shop.setShop_name(shop_name);
        }

        if (shop_open_time!=null){
            shop.setShop_open_time(shop_open_time);
        }

        if (shop_introduce!=null){
            shop.setShop_introduce(shop_introduce);
        }

        if (shop_main_recommend!=null){
            shop.setShop_main_recommend(shop_main_recommend);
        }



        if (request.getParameter("phone")!=null) {
            Integer phone = Integer.valueOf(request.getParameter("phone"));
            shop.setPhone(phone);
        }

        String email= request.getParameter("email");
        shop.setEmail(email);

        //获取product_id
        if (shop_special_recommend_one!=null&&shop_special_recommend_two!=null){
            String shop_special_recommend="{\"shop_special_recommend_one\":\""+shop_special_recommend_one
                    +"\",\"shop_special_recommend_two\":\""+shop_special_recommend_two
                    +"\"}";
            shop.setShop_special_recommend(shop_special_recommend);
        }

        if (shop_notice!=null){
            shop.setShop_notice(shop_notice);
        }

        return shop;
    }
}
